package com.oceansoft.mobile.interceptor;

import com.oceansoft.mobile.common.Constant;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;

public class SessionInterceptor implements Filter {

    private ArrayList<String> safeUrl;
    private PathMatcher matcher;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        Object admin_obj = request.getSession().getAttribute(Constant.GLOBAL_ADMIN_SESSION);
        Object mer_obj = request.getSession().getAttribute(Constant.GLOBAL_SESSION);
        String url = request.getRequestURI().toLowerCase();
        String header = request.getHeader("x-requested-with");
        boolean isAjax = (null != header && header.equalsIgnoreCase("XMLHttpRequest")) || url.endsWith(".json") || url.endsWith(".xml");
        if ( null != admin_obj  ||null != mer_obj  || isSafeUrl(url)) {
            chain.doFilter(servletRequest, servletResponse);
        } else {
            if (isAjax) {
                response.setContentType("application/json;charset=UTF-8");
                Writer writer = response.getWriter();
                writer.write("{\"status\":0,\"code\":259,\"msg\":\"会话超时！\"}");
                writer.flush();
                writer.close();
            } else {
                request.getRequestDispatcher("/WEB-INF/views/errors/timeout.jsp").forward(request, response);
            }
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        String str = config.getInitParameter("excludeUrl");
        safeUrl = new ArrayList<String>();
        safeUrl.add("/*/admin/wxjq/iconpic/*");
        if (StringUtils.hasText(str) && str.split(",").length > 0) {
            matcher = new AntPathMatcher();
            Collections.addAll(safeUrl, str.split(","));
        }
    }

    @Override
    public void destroy() {
        safeUrl.clear();
        safeUrl = null;
    }

    /**
     * 判断是否为安全URL(白名单)
     *
     * @param url 访问URL
     * @return boolean true安全 反之返回false
     */
    private boolean isSafeUrl(String url) {
        for (String item : safeUrl) {
            if (matcher.match(item, url)) {
                return true;
            }
        }
        return false;
    }
}
